package serviceImp;

import java.util.ArrayList;
import java.util.List;

import hibernate_model.Photo;
import hibernate_model.PhotoDAO;
import hibernate_model.User;
import hibernate_model.UserDAO;

import org.springframework.context.ApplicationContext;

import util.FactoryContext;
import net.sf.json.JSONObject;
import m_interface.GetResStr;

public class SearchImp implements GetResStr{
	private JSONObject jsonReq;
	private JSONObject jsonRes;
	private String searchContent;
	private int searchType;
	private List<Photo> photoList = new ArrayList<Photo>();
	private List<User> userList = new ArrayList<User>();
	public SearchImp(String jsonStr){
		jsonReq = JSONObject.fromObject(jsonStr);
		jsonRes = new JSONObject();
		searchContent = jsonReq.getString("searchContent");
	}
	@Override
	public void excute() {
		ApplicationContext ac = FactoryContext.readCof();
		PhotoDAO photoDAO = (PhotoDAO)ac.getBean("PhotoDAO");
		UserDAO userDAO = (UserDAO)ac.getBean("UserDAO");
		switch(searchType){
			case 0:
				userList = userDAO.findByUserNameLikely("%"+searchContent+"%");
				System.out.println("userList"+userList.size());
				jsonRes.put("userSize", userList.size());
				for(int i=0;i<userList.size();i++){
					User user = (User)userList.get(i);
					jsonRes.put("userId"+i, user.getUserId());
					jsonRes.put("userName"+i, user.getUserName());
				}
				break;
			case 1:
				photoList = photoDAO.findByPhotoAddressLikely("%"+searchContent+"%");
				System.out.println("photoList"+photoList.size());
				jsonRes.put("photoSize", photoList.size());
				for(int i=0;i<photoList.size();i++){
					Photo photo = (Photo)photoList.get(i);
					jsonRes.put("photoId"+i, photo.getPhotoId());
					jsonRes.put("photoAddress"+i, photo.getPhotoAddress());
				}
				break;
		}
		
	}
	@Override
	public String ResStr() {
		searchType =0;
		excute();
		searchType =1;
		excute();
		return jsonRes.toString();
	}

}
